// home.js
Page({
  data: {
    isGameStarted: false,
    showResult: false,
    countdown: 10,
    shakeCount: 0,
    highScore: 0,
    timer: null,
    shakeTimer: null
  },

  onLoad: function() {
    // 从本地存储获取最高记录
    const highScore = wx.getStorageSync('shakeHighScore') || 0;
    this.setData({
      highScore: highScore
    });
  },

  // 跳转到当前页面（首页）
  navigateToIndex: function() {
    wx.navigateTo({
      url: '/pages/index/index'
    });
  },

  // 开始甩甩游戏
  startShakeGame: function() {
    this.setData({
      isGameStarted: true,
      showResult: false,
      shakeCount: 0,
      countdown: 10
    });

    // 开启加速度计监听
    this.startAccelerometer();

    // 开始倒计时
    this.startCountdown();
  },

  // 开启加速度计监听
  startAccelerometer: function() {
    const that = this;
    
    // 监听加速度数据
    wx.onAccelerometerChange(function(res) {
      const { x, y, z } = res;
      // 计算加速度向量长度
      const acceleration = Math.sqrt(x * x + y * y + z * z);
      
      // 当加速度超过阈值时计数（阈值可根据需要调整）
      if (acceleration > 2.5) {
        that.setData({
          shakeCount: that.data.shakeCount + 1
        });
      }
    });

    // 开启加速度计
    wx.startAccelerometer({
      interval: 'game'
    });
  },

  // 开始倒计时
  startCountdown: function() {
    const that = this;
    
    this.data.timer = setInterval(function() {
      if (that.data.countdown > 0) {
        that.setData({
          countdown: that.data.countdown - 1
        });
      } else {
        // 倒计时结束
        clearInterval(that.data.timer);
        that.endGame();
      }
    }, 1000);
  },

  // 结束游戏
  endGame: function() {
    // 停止加速度计
    wx.stopAccelerometer();
    wx.offAccelerometerChange();
    
    // 清除定时器
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }

    // 更新最高记录
    const currentScore = this.data.shakeCount;
    const highScore = this.data.highScore;
    
    if (currentScore > highScore) {
      this.setData({
        highScore: currentScore
      });
      // 保存到本地存储
      wx.setStorageSync('shakeHighScore', currentScore);
    }

    this.setData({
      isGameStarted: false,
      showResult: true
    });
  },

  // 重新开始游戏
  restartGame: function() {
    this.startShakeGame();
  },

  // 页面卸载时清理
  onUnload: function() {
    wx.stopAccelerometer();
    wx.offAccelerometerChange();
    
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },

  // 页面隐藏时清理
  onHide: function() {
    wx.stopAccelerometer();
    wx.offAccelerometerChange();
    
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  }
});